package com.sk.bilibili.tool;

import com.sk.bilibili.apiMapper.ApiMapper;
import com.sk.bilibili.bean.Video;
import com.sk.bilibili.service.MinioService;
import com.sk.bilibili.service.VideoService;
import com.sk.bilibili.test4.*;
import com.sk.bilibili.test5.RankInfo;
import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 邵康
 * @date 2021/12/16 12:21
 */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UploadVideoFromBilibili {

    @Autowired
    private MinioService minioService;
    @Autowired
    private ApiMapper apiMapper;
    @Autowired
    private VideoService videoService;
    private static final String URL_PATH = "video/url/%s.flv";
    private OkHttpClient client;
    private VideoApi videoApi;

    @Test
    void test1(){
        videoApi = apiMapper.create(VideoApi.class);
        VideoSetInfo info = videoApi.getVideoSetInfo("BV1gq4y1r72f");
        VideoInfo[] infos = info.getVideoInfos();
        for (VideoInfo temp:infos){
            System.out.println(videoApi.getStreamInfo(info.getAid(),temp.getCid()));
        }
    }

    @Test//根据排行下载
    void test2(){
        client=new OkHttpClient();
        videoApi = apiMapper.create(VideoApi.class);
        Set<String> titles=new HashSet<>();
        int[] types={0,168,1,3,129,4};
        for (int type : types) {
            RankInfo[] rank = videoApi.getRank(type);
            int num=0;
            for (RankInfo aRank : rank) {
                if(aRank.getDuration()>600)continue;//暂不下载 大于 10分钟的
                if(titles.contains(aRank.getTitle()))continue;
                if(num++>50)break;//最多每种下载50个
                titles.add(aRank.getTitle());//防止重复
                VideoInfo info = new VideoInfo(aRank.getCid(), aRank.getTitle(), aRank.getDuration());
                try {//防止下载失败全部取消
                    upload(aRank.getAid(),info);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SneakyThrows
    @Test//根据搜索信息
    void test(){
        int page=1;
        String keyword="宅舞";
        client=new OkHttpClient();
        videoApi = apiMapper.create(VideoApi.class);
        BvInfo[] infos = videoApi.search(page, keyword);
        for (BvInfo info : infos) {
            upload(info.getBvid());
        }
    }

    private void upload(String bvid) {
        VideoSetInfo temp = videoApi.getVideoSetInfo(bvid);
        VideoInfo[] infos = temp.getVideoInfos();
        for (VideoInfo info : infos) {
            if(info.getDuration()>600)continue;//先不下超过 10分钟的
            try {
                upload(temp.getAid(),info);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    private void upload(Integer aid, VideoInfo info) throws Exception {
        StreamInfo streamInfo = videoApi.getStreamInfo(aid, info.getCid());
        InputStream is = client.newCall(new Request.Builder().url(streamInfo.getUrl())
                .header("referer", "https://www.bilibili.com/")
                .header("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .build()).execute().body().byteStream();
        String url = minioService.uploadStream(is, streamInfo.getSize(),URL_PATH);
        Video video = new Video();
        video.setTitle(info.getPart());
        video.setDuration(info.getDuration());
        video.setVideoSetId(0);
        video.setUrl(url);
        videoService.save(video);
        System.out.println(video);
    }

}
